package manong.serviceimpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import manong.beans.*;
import manong.constant.Constant;
import manong.constant.ServerResponse;
import manong.mapper.StuMapper;
import manong.mapper.TeacherMapper;
import manong.mapper.UserMapper;
import manong.service.IUserService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StuMapper stuMapper;
    @Autowired
    private TeacherMapper teacherMapper;

    @Override
    public ServerResponse<String> add(String username, String password, String role, String mark) {
        UserQuery query = new UserQuery();
        query.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(query);
        if (users.size() > 0) {
            return ServerResponse.createByErrorMessage("用户已经存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(role);
        user.setMark(mark);
        int count = userMapper.insertSelective(user);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("用户创建成功");
        }
        return ServerResponse.createByErrorMessage("用户创建失败");
    }

    @Override
    public ServerResponse<User> login(String username, String password, String role) {
       ////此为判断学生登录
        if(Constant.STU.equals(role)){   //加了一个常量        //打断点显示：role：学生，role是当前账号的身份，如果是学生会走这个循环，不是会跳下面
            //创建学生查询对象
        	StuQuery stuQuery = new StuQuery();
            stuQuery.createCriteria().andSnoEqualTo(Integer.parseInt(username));//先查询，根据学号去查有没有对应的用户
            //为null的话账号信息错误，查询不到
            Stu stu = stuMapper.selectOneByExample(stuQuery);
       ////查询是否有对应的学生     
            if (stu != null) {
            	//根据手机号的后四位与当前的password进行比较，正确的话走下去
       ////根据学生的手机号后四位当做密码进行判断登录是否成功     	
                String studentPhone = stu.getStudentPhone();
                String stuPassword = studentPhone.substring(7);
      ////登录失败直接返回错误          
                if (!stuPassword.equals(password)) ServerResponse.createByErrorMessage("账号信息错误");//反向判断可以快速调整代码
      ////登陆成功封装数据，将学生的姓名和学号存入user再存入session中         
                User user = new User(); //user用于全局数据，相当于这个学生端的查课表只需要查周数就行，班级老师名不需要填，但是要用这两个去查询
                user.setUsername(stu.getStudentName());//username是当前学生的一个信息
                user.setRole("学生");//身份是学生
                user.setStatu(0);
                user.setMark(String.valueOf(stu.getSno()));//所以将数据给重置里面了
                //数据库里没有对应字段，就先用mark存学号
       ////返回 数据        
                return ServerResponse.createBySuccess("登录成功", user);//设置好之后进行返回--》con
            }else{
                return ServerResponse.createByErrorMessage("账号信息错误");
            }
        }
        //此为判断教师登录
        if(Constant.TEC.equals(role)){
            TeacherQuery teacherQuery = new TeacherQuery();
            teacherQuery.createCriteria().andTeacherPhoneEqualTo(username);
            Teacher teacher = teacherMapper.selectOneByExample(teacherQuery);
            if (teacher != null) {
                String teacherPhone = teacher.getTeacherPhone();
                String teacherPassword = teacherPhone.substring(7);
                if (!teacherPassword.equals(password)) ServerResponse.createByErrorMessage("账号信息错误");
                User user = new User();
                user.setUsername(teacher.getTeacherName());
                user.setRole("教师");
                user.setStatu(0);
                user.setMark(String.valueOf(teacher.getTeacherPhone()));
                return ServerResponse.createBySuccess("登录成功", user);
            }else{
                return ServerResponse.createByErrorMessage("账号信息错误");
            }
        }
        //此为判断除学生外登录
        UserQuery query = new UserQuery();
        query.createCriteria().andUsernameEqualTo(username).andPasswordEqualTo(password).andRoleEqualTo(role);
        User user = userMapper.selectOneByExample(query);
        if (user != null) {
            user.setPassword("");
            return ServerResponse.createBySuccess("登录成功", user);
        }
        return ServerResponse.createByErrorMessage("账号信息错误");
    }

    @Override
    public ServerResponse<String> del(Integer id) {
        int count = userMapper.deleteByPrimaryKey(id);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }

    @Override
    public ServerResponse<PageInfo<User>> findAll(String role, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        UserQuery query = new UserQuery();
        List<User> users;
        PageInfo<User> pageInfo;
        if (role.equals(Constant.ADMIN)) {
            users = userMapper.selectByExampleWithRowbounds(query, new RowBounds((pageNum - 1) * 10, pageSize));
            pageInfo = new PageInfo<>(users);
            pageInfo.setTotal(userMapper.countByExample(query));

        } else {
            query.createCriteria().andRoleEqualTo(Constant.NOT_ADMIN);
            users = userMapper.selectByExampleWithRowbounds(query, new RowBounds((pageNum - 1) * 10, pageSize));
            pageInfo = new PageInfo<>(users);
            pageInfo.setTotal(userMapper.countByExample(query));
        }
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse<User> findById(Integer id) {
        return ServerResponse.createBySuccess(userMapper.selectByPrimaryKey(id));
    }

    @Override
    public ServerResponse<String> update(Integer id, String username, String password, String role,String mark) {
        User user = userMapper.selectByPrimaryKey(id);
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(role);
        user.setMark(mark);
        int count = userMapper.updateByPrimaryKeySelective(user);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("更新成功");
        }
        return ServerResponse.createByErrorMessage("更新失败");
    }
}
